from utils.tools import get_path
import os
import time
from playwright.sync_api import sync_playwright, expect, Page

# URL_L = "https://pingcode.com/signin"
URL_L = "https://192.168.4.195/wgglMgr"


class Page_Object:
    def __init__(self, page: Page):
        self.page = page
        def_timeout = 10000
        self.page.set_default_timeout(def_timeout)  # 默认超时时间
        self.page.set_default_navigation_timeout(def_timeout)  # 导航栏

    def navigate(self):
        self.跳转()

    def 跳转(self, path: str = None):

        if path[0] != '/':
            path = f'/{path}'
        self.page.goto(f'{self.page.url.split("wgglMgr")[0]}wgglMgr{path}')

    def page_login_save_cookies(self, user_name: str, password: str):
        """
        通过页面登录
        :param user_name:
        :param usernaem:
        :param password:
        :return:
        """

        # os.path.getatime(f"{user_name}.txt" 文件的创建时间
        # page.pause()

        # if os.path.exists(get_path(f"/.auth/{user_name}.txt")) and int(
        #         time.time() - os.path.getatime(get_path(f"/.auth/{user_name}.txt"))) < 86400:
        #     with open(get_path(f"/.auth/{user_name}.txt")) as f:
        #         cookies = f.read()
        #     cookies = eval(cookies)  # 转换文档原格式
        #     self.page.context.add_cookies(cookies)
        #     self.page.goto(URL_L)
        # else:
        self.page.goto(URL_L)
        self.page.get_by_placeholder("请输入用户名").type(user_name, delay=20)
        self.page.get_by_placeholder("请输入登录密码").fill(password)
        self.page.get_by_text("登 录 ").click()
        self.page.wait_for_timeout(3000)
        expect(self.page.locator('.user-name').first).to_be_visible()  # to_be_visible 判断是否存在
            # cookies = self.page.context.cookies()  # page.context.cookies() 获取登录的cookie
            # with open(get_path(f"/.auth/{user_name}.txt"), "w") as f:
            #     f.write(str(cookies))
